const userModel = require('../models/userModel');

// 工具函数：简单校验
function isValidUsername(username) {
    return typeof username === 'string' && /^[A-Za-z0-9]{3,16}$/.test(username);
}
function isValidPassword(password) {
    return typeof password === 'string' && password.length >= 6 && password.length <= 32;
}
function isValidNickname(nickname) {
    return typeof nickname === 'string' && nickname.length >= 1 && nickname.length <= 12;
}

const login = (req, res) => {
    const { username, password } = req.body;
    if (!isValidUsername(username) || !isValidPassword(password)) {
        return res.status(400).json({msg: '账号或密码格式不正确'});
    }
    userModel.loginUser(username, password)
        .then((rs)=> {
            if (rs.length === 0) return res.status(401).json({msg: '账号或密码错误'});
            return res.status(200).send(rs[0]);
        })
        .catch(err => {
            console.error(err)
            return res.status(500).json({msg: '当前无法登录，请稍后重试'});
        });
}

const checkUserExist = (req, res) => {
    const username = req.query.username
    if (!isValidUsername(username)) {
        return res.status(400).json({msg: '账号格式不正确'});
    }
    userModel.getUserByUsername(username).then(rs => {
        if (rs[0]["count"] === 1) {
            return res.status(200).send('taken')
        } else {
            return res.status(200).send('pass')
        }
    }).catch(err => {
        console.error(err)
        return res.status(500).json({msg: '检查内容失败，服务器错误'})
    })
}

const reg = (req, res) => {
    // 兼容 form-data 和 json
    const { username, name, password } = req.body;
    let avatar = req.file ? req.file.filename : 'unset_pfp.jpg';
    // 参数校验
    if (!isValidUsername(username)) {
        return res.status(400).json({msg: '账号格式不正确，仅限3-16位字母或数字'});
    }
    if (!isValidNickname(name)) {
        return res.status(400).json({msg: '昵称需为1-12字符'});
    }
    if (!isValidPassword(password)) {
        return res.status(400).json({msg: '密码长度需为6-32位'});
    }
    // 头像类型和大小校验（如果有文件）
    if (req.file) {
        const allowTypes = ['image/jpeg', 'image/png', 'image/jpg'];
        if (!allowTypes.includes(req.file.mimetype)) {
            return res.status(400).json({msg: '头像仅支持jpg/png格式'});
        }
        if (req.file.size > 2 * 1024 * 1024) {
            return res.status(400).json({msg: '头像最大2MB'});
        }
    }
    // 检查用户名是否已存在
    userModel.getUserByUsername(username).then(rs => {
        if (rs[0]["count"] === 1) {
            return res.status(409).json({msg: '账号已存在'});
        }
        // 创建账号
        const createAccountInfo = [username, name, password, avatar];
        userModel.createUser(createAccountInfo).then((rs) => {
            return res.status(200).send(rs)
        }).catch(err => {
            return res.status(500).json({msg: '服务器错误，当前无法创建账号', err})
        })
    }).catch(err => {
        return res.status(500).json({msg: '服务器错误，无法校验账号', err})
    })
}

const getJoinedGroups = (req, res) => {
    const uid = req.params.uid
    userModel.getGroupsByUserId(uid).then(rs => {
        return res.status(200).send(rs)
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '获取群聊列表失败'})
    })
}

const getInbox = (req, res) => {
    const uid = req.query.uid
    userModel.getInboxByUserId(uid).then(rs => {
        return res.status(200).send(rs)
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '服务器错误，无法获取通知'})
    })
}

const checkProfile = (req, res) => {
    const uid = req.query.uid

    userModel.getUserProfileByUid(uid).then(rs => {
        return res.status(200).send(rs)
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '获取资料失败'})
    })
}

const updateNickname = (req, res) => {
    const fields = Object.values(req.body)
    userModel.updateNicknameByUid(fields).then(rs => {
        return res.status(200).end()
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '更新失败，请稍后重试'})
    })
}

const updateAvatar = (req, res) => {
    if (!req.file) return res.status(401).end()

    const fields = Object.values(req.body)
    fields.unshift(req.file.filename)

    userModel.updateAvatarByUid(fields).then(rs => {
        return res.status(200).end(req.file.filename)
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '更新失败，请稍后重试'})
    })
}

const getUserSetting = (req, res) => {
    const uid = req.query.uid

    userModel.getUserSettingByUid(uid).then(rs => {
        return res.status(200).send(rs)
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '获取设置失败'})
    })
}



const changeTheme = (req, res) => {
    const uid = req.body.uid

    userModel.changeUserThemeByUid(uid).then(rs => {
        return res.status(200).end()
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '操作失败，稍后重试'})
    })
}

const updatePrivacy = (req, res) => {
    const uid = req.body.uid

    userModel.changePrivacyByUid(uid).then(rs => {
        return res.status(200).send(rs)
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '操作失败，稍后重试'})
    })
}

const getConversations = (req, res) => {
    const {uid} = req.query
    userModel.getConversationsByUid(uid).then(rs => {
        return res.status(200).send(rs)
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '获取对话列表失败'})
    })
}

const getFullProfile = (req, res) => {
    const {uid} = req.query
    userModel.getFullProfile(uid).then(rs => {
        return res.status(200).send(rs)
    }).catch(err => {
        console.error(err)
        return res.status(500).send({msg: '获取资料失败'})
    })
}

module.exports = {
    login,
    reg,
    checkUserExist,
    checkProfile,
    getJoinedGroups,
    getInbox,
    updateNickname,
    updateAvatar,
    getUserSetting,
    changeTheme,
    updatePrivacy,
    getConversations,
    getFullProfile
};